package com.hmall.order.interceptor;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * TODO
 *
 * @Author mr.ma
 * @Date 2024/11/22 14:37
 */
@Component
public class Admininterceptor implements HandlerInterceptor {


    private static final ThreadLocal<Long> userIdThreadLocal = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 从请求头中获取authorization信息，这里假设它就是userId，实际应用中可能需要解析等操作
        String authorization = request.getHeader("authorization");
        if (authorization!= null) {
            try {
                Long userId = Long.parseLong(authorization);
                userIdThreadLocal.set(userId);
            } catch (NumberFormatException e) {
                // 如果无法转换为Long类型，可根据业务需求进行相应处理，比如记录日志、返回错误响应等
                // 这里简单打印日志示例
                System.err.println("无法将authorization信息转换为Long类型的userId");
                e.printStackTrace();
            }
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        userIdThreadLocal.remove();
    }


    public static Long getUserId() {
        return userIdThreadLocal.get();
    }

}



